﻿using Common;
using Common.Entity;
using Common.Utility;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CodeToolBox.Form
{
    public partial class SchemaDec : UIForm
    {
        public SchemaDec()
        {
            InitializeComponent();
        }

        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Control && e.KeyCode == Keys.V)
                {
                    string clipboardText = Clipboard.GetText();
                    string[] lines = clipboardText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                    // 创建一个 DataTable 来存储第二列和第三列的数据
                    DataTable dataTable = new DataTable();
                    dataTable.Columns.Add("字段名");
                    dataTable.Columns.Add("字段描述");
                    // 遍历每一行
                    foreach (string line in lines)
                    {
                        // 拆分每行中的列
                        string[] columns = line.Split('\t');

                        // 检查是否有足够的列数
                        if (columns.Length >= 3)
                        {
                            // 添加第二列和第三列的数据到 DataTable
                            dataTable.Rows.Add(columns[1], columns[2]);
                        }
                    }
                    dataGridView1.DataSource = dataTable;
                    e.Handled = true; // 标记事件已经处理，防止默认粘贴操作执行
                }
            }
            catch (Exception ex)
            {
                ShowErrorTip(ex.Message, 1500);
                //MessageBox.Show(ex.Message);
            }
        }

        private void SchemaDec_Load(object sender, EventArgs e)
        {
            try
            {
                string fileurl = Config.BeflamInIUrl;
                if (File.Exists(fileurl))
                {
                    text_url.Text = INIHelper.INIRead("配置信息", "URL", fileurl);
                    text_session.Text = INIHelper.INIRead("配置信息", "SessionID", fileurl);
                    text_appid.Text = INIHelper.INIRead("配置信息", "AppID", fileurl);
                    text_table.Text = INIHelper.INIRead("配置信息", "Table", fileurl);
                }
                else
                {
                    string folderPath = fileurl.Split((fileurl.Split("\\").Last()))[0];
                    if (!Directory.Exists(folderPath))
                    {
                        Directory.CreateDirectory(folderPath);
                    }
                    writerSetting();
                }
            }
            catch (Exception ex)
            {
                ShowErrorNotifier(ex.Message, true, 5000);
            }
        }

        private void writerSetting()
        {
            try
            {
                string fileurl = Config.BeflamInIUrl;
                INIHelper.INIWrite("配置信息", "URL", text_url.Text, fileurl);
                INIHelper.INIWrite("配置信息", "SessionID", text_session.Text, fileurl);
                INIHelper.INIWrite("配置信息", "AppID", text_appid.Text, fileurl);
                INIHelper.INIWrite("配置信息", "Table", text_table.Text, fileurl);


            }
            catch (Exception ex)
            {

                ShowErrorNotifier(ex.Message, true, 5000);
            }
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiButton1_Click(object sender, EventArgs e)
        {
            try
            {
                writerSetting();
                ShowSuccessTip("保存成功", 1500);
            }
            catch (Exception ex)
            {

                ShowErrorNotifier(ex.Message, true, 5000);
            }
        }

        /// <summary>
        /// 对比
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiButton2_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(text_url.Text.Trim())) throw new Exception("url不能为空");
                if (string.IsNullOrWhiteSpace(text_session.Text.Trim())) throw new Exception("sessionID不能为空");
                if (string.IsNullOrWhiteSpace(text_appid.Text.Trim())) throw new Exception("应用名不能为空");
                if (string.IsNullOrWhiteSpace(text_table.Text.Trim())) throw new Exception("表名不能为空不能为空");
                string urlstr = text_url.Text.Trim();
                string sessionid = text_session.Text.Trim();
                string appid = text_appid.Text.Trim();
                string tablestr = text_table.Text.Trim();



                //获取Schema
                BeflamToolManager manager = new BeflamToolManager();
                SchemaData schema = manager.GetSchema(urlstr, appid, sessionid, tablestr);
                List<DataSourceItemex> NewDataSourceItem = new List<DataSourceItemex>();
                foreach (DataSourceItem item in schema.data.DataSource)
                {
                    int rowIndex = dataGridView1.Rows
                        .Cast<DataGridViewRow>()
                        .Select(r => r.Cells[0].Value?.ToString())
                        .ToList()
                        .FindIndex(value => value != null && value.Contains(item.FLD_NAME));
                    if (rowIndex != -1)
                    {
                        string fielddec = dataGridView1.Rows[rowIndex].Cells[1].Value.ToString();
                        if (fielddec != item.FLD_DESCRIPTION)
                        {

                            //DataSourceItemex sourceItem = new DataSourceItemex();
                            DataSourceItemex sourceItem = manager.ConvertST(item);
                            sourceItem.FLD_DESCRIPTION = fielddec;
                            NewDataSourceItem.Add(sourceItem);
                        }
                    }
                }
                if (NewDataSourceItem.Count > 0)
                {
                    manager.SaveScheam(urlstr, appid, sessionid, tablestr, NewDataSourceItem);
                }
                ShowSuccessTip($"修改成功{NewDataSourceItem.Count()}个字段描述！", 3000);

            }
            catch (Exception ex)
            {

                ShowErrorNotifier(ex.Message, true, 5000);
            }
        }
    }
}
